/**
* ...
* @author Default
* @version 0.1
*/

package org.hive.utils.performance 
{
	import org.hive.managers.plugin.LayoutManager;
	import flash.display.LineScaleMode;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.filters.GlowFilter;
	import flash.utils.Timer;
	import flash.system.System;

	public class MemoryTracker extends Sprite
	{		
		private static var __timer:Timer = new Timer( 100, 0 );
		private static var __display:Sprite = new Sprite( );
		
		private static var widthOnInit:Number;
		private static var heightOnInit:Number;
		
		public function MemoryTracker( )
		{
			trace("MemoryTracker :: init");
			
			widthOnInit = LayoutManager.stageWidth;
			heightOnInit = LayoutManager.stageHeight;
			
			//graphics.beginFill( 0x00, 0.6 );
			//graphics.drawRect( 0, 0, widthOnInit, heightOnInit );
			
			__display.graphics.beginFill( 0x33FF33, 0 );
			__display.graphics.lineStyle( 1, 0x33FF33, 0.4, true, LineScaleMode.NONE );			
			__display.graphics.moveTo( 0, LayoutManager.stageHeight );
			//__display.filters = [ new GlowFilter( 0x33FF33, 1, 1, 1 ) ];
			
			addChild( __display );
			
			__timer.addEventListener( TimerEvent.TIMER, updateDisplay, false, 0, true );
			__timer.start();
			
			addEventListener( MouseEvent.MOUSE_DOWN, enableDrag );
			addEventListener( MouseEvent.MOUSE_UP, disableDrag );
		}
		
		private function enableDrag( e:MouseEvent ):void
		{
			startDrag( false );
		}
		
		private function disableDrag( e:MouseEvent ):void
		{
			stopDrag( );
		}
		
		//_______________________________________________________________________ DISPLAY
		private static var __maxMemory:Number;
		private static function updateDisplay( e:TimerEvent ):void
		{
			var totalMemory = System.totalMemory;
            __maxMemory = Math.max( __maxMemory, totalMemory );			
			
			var memoryScaled:Number = totalMemory / 102400;
			var secondsElapsed:Number = ( __timer.delay * __timer.currentCount ) / 100;

			__display.graphics.moveTo( secondsElapsed, heightOnInit );
			__display.graphics.lineTo( secondsElapsed, heightOnInit - memoryScaled );
		}
		
		
		
		//______________________________________________________________________ GETTERS
		public static function get currentMemory( ):Number
		{
			return System.totalMemory;
		}
				
		public static function get peakMemory( ):Number
		{
			return __maxMemory;
		}
	}
	
}
